package com.googlecode.continuity.core.server.mvc.validation;

import org.acegisecurity.context.SecurityContextHolder;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import com.googlecode.continuity.core.server.mvc.command.EditUserCommand;
import com.googlecode.continuity.core.server.security.SecurityUserToken;

/**
 * EditAccountValidator is used to check a changes to a user account. In addition to the checks performed by the
 * {@link EditUserValidator} this class makes sure that the
 * submitted passwords are valid and equal and that the old password is correct.
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class EditAccountValidator extends EditUserValidator {
  /**
   * Compares and validates both submitted passwords if they have been changed.  An error is written if the new
   * passwords are not equal, not valid or if the old password supplied is not correct. The old password is only
   * necessary when a new password is set.
   *
   * @param command submitted command
   * @param errors error object into which errors can be written
   */
  public void checkPasswords(EditUserCommand command, Errors errors) {
    if ((command.getNewpass1() != null && !command.getNewpass1().equals("")) ||
        (command.getNewpass2() != null && !command.getNewpass2().equals(""))) {
      if (!command.getNewpass1().equals(command.getNewpass2())) {
        errors.rejectValue("newpass1", "error.password.noMatch");
        errors.rejectValue("newpass2", "error.password.noMatch");
      }
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "oldpass", "error.password.required");
      if (!getUserService().isCorrectPassword(
          (SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
          command.getOldpass())) {
        errors.rejectValue("oldpass", "error.password.wrong");
      }
      validatePassword("newpass1", command.getNewpass1(), errors);
    }
  }
}
